class Solution {
    int ret;
    boolean[][] vist;
    int m, n;
    public int getMaximumGold(int[][] grid) {
        m = grid.length; n = grid[0].length;
        vist = new boolean[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] != 0) {
                    vist[i][j] = true;
                    dfs(grid, i, j, grid[i][j]);
                    vist[i][j] = false;//恢复现场
                }
            }
        }
        return ret;
    }
    //向量数组
    int[] dx = {0, 0, -1, 1};
    int[] dy = {-1, 1, 0, 0};
    public void dfs(int[][] grid, int i, int j, int path) {
        //两种写法，一种是path初始化为0，这里要函数体内要加一次
        // //当前位置和
        // sum += grid[i][j];
        // //判断路径
        // if(ret < sum) ret = sum;

        //另一种写法，把计算结果放在参数里，就不用写在函数体内了
        ret = Math.max(ret, path);
        //遍历当前位置的四个方向
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && vist[x][y] == false && grid[x][y] != 0) {
                vist[x][y] = true;
                dfs(grid, x, y, path + grid[x][y]);
                vist[x][y] = false;//恢复现场
            }
        }
    }
}